package com.dbsop.operation.index;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;

import java.io.IOException;

@Slf4j
public class RestIndexOperation implements IndexOperation {

    private RestHighLevelClient restClient;

    public RestIndexOperation(RestHighLevelClient restClient) {
        this.restClient = restClient;
    }


    @Override
    public boolean existsIndex(String index) {
        GetIndexRequest indexRequest = new GetIndexRequest(index);
        try {
            return restClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void checkCreateIndex(IndexParams indexParams) {
        if (!existsIndex(indexParams.getIndexName())) {
            log.info("索引不存在: " + indexParams.getIndexName());
            createIndex(indexParams);
        }
    }

    @Override
    public void createIndex(IndexParams indexParams) {
        String indexName = indexParams.getIndexName();
        String alias = indexParams.getAlias();
        Integer maxResult = indexParams.getMaxResult();
        Integer replicas = indexParams.getReplicas();
        Integer shared = indexParams.getShared();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        Settings.Builder builder = Settings.builder();
        Settings settings = null;
        if (alias!=null && !alias.trim().equals("")){
            createIndexRequest.alias(new Alias(alias));
        }
        if (shared != null && shared >0 ){
            builder.put("number_of_shards", shared);
        }
        if (replicas != null && replicas >0){
            builder.put("number_of_replicas", replicas);
        }
        if (maxResult!=null && maxResult >0){
            builder.put("max_result_window", maxResult);
        }
        createIndexRequest.settings(builder);
        boolean acknowledged = false;
        try {
            acknowledged = restClient.indices().create(createIndexRequest, RequestOptions.DEFAULT).isAcknowledged();
            if (acknowledged) log.info("索引创建成功: " + indexName+"; 分片为:" +shared +"; 副本数量为:" + replicas);
            else log.info("索引创建失败: " + indexName);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("索引创建异常: " + indexName);
        }

    }

}
